import doRequest from './doRequest'
import location from '@/utils/location'
import loading from './loading'
import login from '@/utils/login'
import authority from '@/utils/authority'
import { getCurrentUrl } from '@/utils'

// 错误尝试次数
const maxCount = 2

// 获取地址位置
async function getLocation() {
  try {
    const user = authority.get() || {}
    if (user.regionCode) return true
    const { city, region_code } = await location.get()
    authority.set({ currentCity: city, regionCode: region_code })
  } catch (e) {
    console.error(e)
    const back = getCurrentUrl()
    if (back.startswith('/pages/chooseCity/main')) {
      return
    }
    wx.navigateTo({
      url: `/pages/chooseCity/main?back=${back}`
    })
    return Promise.reject(e)
  }
}

// 最终求情封装
export default async (
  options,
  { shouldLoading = true, needLogin = false, needLocation = false } = {}
) => {
  if (needLogin) {
    await login()
  }

  if (needLocation) {
    await getLocation()
  }

  if (shouldLoading) loading.show()
  for (let i = 0; i < maxCount; i++) {
    try {
      const data = await doRequest(options)
      if (shouldLoading) loading.hide()
      return data
    } catch (e) {
      // 再次尝试
      if (i < maxCount) {
        // 401重新登陆
        if (e && e.statusCode === 401) {
          authority.clear()
          loading.hide(true)
          await login()
        }
        continue
      }

      // 返回最终错误
      if (shouldLoading) loading.hide()
      return Promise.reject(e)
    }
  }
}
